/*
 * FilePath     : \src\components\univerSheet\hooks\useUniverUtil.ts
 * Author       : 苏军志
 * Date         : 2024-10-14 19:04
 * LastEditors  : 苏军志
 * LastEditTime : 2025-03-12 17:56
 * Description  : univer相关逻辑
 * CodeIterationRecord:
 */
import { Observable } from "rxjs";
import { type ICommand, CommandType, FUniver } from "@univerjs/presets";
import { MenuItemType } from "@univerjs/presets/preset-sheets-core";
import { cellBaseStyle } from "../style/cellBaseStyle";
import type { configType } from "../types/configType";
import type { customMenuDataType } from "../types/customMenuDataType";
import { menuEnum } from "../types/menuEnum";
export function useUniverUtil(config: configType) {
  /**
   * @description: 获取Univer初始化参数
   * @return
   */
  const getConfig = () => {
    return {
      showHeader: config.showHeader !== undefined ? config.showHeader : true,
      showToolbar: config.showToolbar !== undefined ? config.showToolbar : true,
      showFormula: config.showFormula !== undefined ? config.showFormula : true,
      showFooter: config.showFooter !== undefined ? config.showFooter : true,
      headerRowCount: config.headerRowCount || 0,
      showRowIndexEnd: config.showRowIndexEnd,
      headerFontColor: config.headerFontColor || "#000000",
      showMenuList: config.showMenuList || [],
      headerBackgroundColor: config.headerBackgroundColor || "#ffffff",
      onUndo: config.onUndo,
      onRedo: config.onRedo,
      onClearCell: config.onClearCell,
      onColumnChange: config.onColumnChange,
      onMoveRows: config.onMoveRows,
      onBeforeCellDataChange: config.onBeforeCellDataChange,
      onCellDataChange: config.onCellDataChange,
      // onCommentChange: config.onCommentChange,
      onCellHover: config.onCellHover
    };
  };
  /**
   * @description: 将普通数组转换为自定义菜单
   * @param customMenuData 菜单数据
   * @param univerAPI univer组件接口对象
   * @param parentID 父id
   * @return
   */
  const getMenuData = (
    customMenuData: customMenuDataType[],
    commands: ICommand[],
    menus: Record<string, Record<string, any>>,
    univerAPI: FUniver,
    parentID?: string
  ) => {
    customMenuData.forEach((customMenu: customMenuDataType, index: number) => {
      const type = customMenu.menuData.children?.length ? MenuItemType.SUBITEMS : MenuItemType.BUTTON;
      const typeName = customMenu.menuData.children?.length ? "dropdown-list" : "button";
      const title = (customMenu.keyMap ? customMenu.menuData[customMenu.keyMap.title] : customMenu.menuData.title) || "";
      const menuID = (customMenu.keyMap ? customMenu.menuData[customMenu.keyMap.id] : customMenu.menuData.id) || "";
      const id = parentID ? `${parentID}.${menuID}` : `custom-menu.operation.${typeName}.${menuID}`;
      // 如果没有子项，直接加入命令
      if (!customMenu.menuData.children?.length) {
        commands.push({
          id: id,
          type: CommandType.OPERATION,
          handler: async (accessor: any) => {
            customMenu.callback && (await customMenu.callback(customMenu.menuType, customMenu.menuData, univerAPI));
            return true;
          }
        });
      }
      let menu = {
        order: index + 10,
        menuItemFactory: () => {
          let menu: Record<string, any> = {
            id: id,
            type: type,
            icon: (customMenu.keyMap ? customMenu.menuData[customMenu.keyMap.icon] : customMenu.menuData.icon) || "",
            tooltip: (customMenu.keyMap ? customMenu.menuData[customMenu.keyMap.tooltip] : customMenu.menuData.tooltip) || "",
            title: title,
            disabled$: new Observable<boolean>((subscriber) => {
              if (customMenu.getDisabled) {
                const disabled = customMenu.getDisabled(customMenu.menuType, menuID, univerAPI);
                // console.log("disabled", disabled);
                subscriber.next(disabled);
              } else {
                subscriber.next(false);
              }
            }),
            activated$: new Observable<boolean>((subscriber) => {
              if (customMenu.getActivated) {
                subscriber.next(customMenu.getActivated(customMenu.menuType, menuID, univerAPI));
              } else {
                subscriber.next(false);
              }
            })
          };
          parentID && (menu.positions = [parentID]);
          return menu;
        }
      };
      if (!parentID) {
        !menus[id] && (menus[id] = menu);
      } else {
        if (!menus[parentID]) {
          menus[parentID] = {};
        }
        menus[parentID][id] = menu;
      }
      if (customMenu.menuData.children?.length) {
        const menuData = getMenuData(customMenu.menuData.children, commands, menus, univerAPI, id);
        commands = menuData.commands;
        menus = menuData.menus;
      }
    });
    return { commands, menus };
  };
  return {
    /**
     * @description: 获取配置菜单
     * @param showMenuList
     * @return
     */
    getHideMenuList(showMenuList: menuEnum[]) {
      let hiddenMenuList: Record<string, any> = {};
      for (const key in menuEnum) {
        const value = (menuEnum as any)[key as keyof menuEnum];
        if (showMenuList?.length && !showMenuList.includes(value)) {
          hiddenMenuList[value] = { hidden: true };
        }
      }
      return hiddenMenuList;
    },
    /**
     * @description: 单元格基础样式
     */
    cellBaseStyle,
    /**
     * @description: 十六进制颜色转RGB
     * @param hex
     * @return
     */
    hexToRgb(hex: string) {
      // 使用正则表达式匹配16进制的颜色值，并提取RGB三个分量的值
      const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      if (match) {
        // 将提取的16进制分量转换为十进制数字
        const red = parseInt(match[1], 16);
        const green = parseInt(match[2], 16);
        const blue = parseInt(match[3], 16);
        // 返回RGB值组成的数字数组
        return [red, green, blue];
      }
    },
    /**
     * @description: 获取Univer初始化参数
     */
    getConfig,
    /**
     * @description: 将排班模板数据表转换为univer单元格数据格式
     * @param rowCount 行数
     * @param columnCount 列数,可大于tableData.columns列数
     * @param tableData 后端返回的模板明细数据
     * @param noonList 午别
     * @return
     */
    tableViewConvertCellData(rowCount: number, columnCount: number, tableData: TableView, setCellData?: Function) {
      const initCconfig = getConfig();
      const { rows, columns } = tableData;
      let cellData: Record<string, Record<string, any>> = {};
      for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
        let columnData: Record<string, any> = {};
        for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {
          // 判断是否为标题  标题特殊处理
          if (rowIndex < initCconfig.headerRowCount!) {
            let title = "";
            if (columnIndex < columns.length) {
              if (rowIndex === 0) {
                title = columns[columnIndex]?.name;
              } else {
                if (columns[columnIndex].childColumns?.length) {
                  title = columns[columnIndex].childColumns![0]?.name;
                }
              }
            }
            columnData[columnIndex] = {
              v: title,
              s: "header-cell-style"
            };
            continue;
          }
          let value = { v: "", s: "cell-style" };
          const index = rowIndex - initCconfig.headerRowCount!;
          if (columnIndex < columns.length && index < rows.length) {
            const data = rows[index][columns[columnIndex].key];
            if (data) {
              if (setCellData) {
                value = setCellData({ data, rowIndex: index, columnIndex, row: rows[index], column: columns[columnIndex] });
              }
            }
          }
          columnData[columnIndex.toString()] = value;
        }
        cellData[rowIndex.toString()] = columnData;
      }
      return cellData;
    },
    convertMenu(customMenuData: customMenuDataType[], univerAPI: FUniver) {
      let commands: ICommand[] = [];
      let menus: Record<string, Record<string, any>> = {};
      // 递归将普通数组转换为自定义菜单
      const menuData = getMenuData(customMenuData, commands, menus, univerAPI);
      return menuData;
    }
  };
}
